﻿using System;
using System.ComponentModel;
using System.IO;
using System.Net;

namespace Gpf.Whs.YouTubeDownloader.CommSrv
{
    public class DownloadItem : IDisposable
    {
        public string Key { get; set; }
        public string Title { get; set; }
        public string Format { get; set; }
        public long Length { get; set; }
        public long CurrentlyDownloaded { get; set; }
        public int PercentDownloaded { get; set; }
        public string Url { get; set; }
        public string TargetPath { get; set; }
        public string FullPath { get; set; }

        public delegate void DownloadDoneDeletage(string key);
        public event DownloadDoneDeletage DownloadDone;

        private object _lock = new object();
        private WebClient _client = new WebClient();

        public void Download(object context)
        {
            _client.DownloadProgressChanged += DownloadProgressChanged;
            _client.DownloadFileCompleted += DownloadFileCompleted;

            var fileName = Title;
            if (string.IsNullOrEmpty(fileName))
                fileName = Key;

            fileName = fileName.Replace("\\", "");
            fileName = fileName.Replace("/", "");
            fileName = fileName.Replace(":", "");
            fileName = fileName.Replace("*", "");
            fileName = fileName.Replace("?", "");
            fileName = fileName.Replace("\"", "");
            fileName = fileName.Replace("<", "");
            fileName = fileName.Replace(">", "");
            fileName = fileName.Replace("|", "");

            FullPath = Path.Combine(TargetPath, fileName + ".mp4");

            _client.DownloadFileAsync(new Uri(Url),FullPath);           
        }

        public void StopDownload()
        {
            _client.CancelAsync();            
        }

        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (DownloadDone != null)
                DownloadDone(Key);
        }

        private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            lock (_lock)
            {
                CurrentlyDownloaded = e.BytesReceived;
                PercentDownloaded = e.ProgressPercentage;
            }
        }

        public void Dispose()
        {
            _client.Dispose();
        }
    }
}
